﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NaturalNote.Core
{
    public static class TypeHelper
    {
        public static bool IsBool(this Type type)
        {
            return type == typeof(bool);
        }
        public static bool IsString(this Type type)
        {
            return (type == typeof(string));
        }
        public static bool IsDateTime(this Type type)
        {
            return type == typeof(DateTime);
        }
        public static bool IsNumber(this Type t)
        {
            return
                 t == typeof(int)
                 || t == typeof(long)
                 || t == typeof(decimal)
                 || t == typeof(double)
                 || t == typeof(float)
                 || t == typeof(uint)
                 || t == typeof(ulong)
                 || t == typeof(ushort)
                 || t == typeof(short);            
        }
        public static bool IsValueType(this Type type)
        {
            return type.IsValueType
                   || type == typeof(string)
                   || type == typeof(DateTime)
                   || type.IsEnum;
        }
        public static bool IsArray(this Type type, out Type itemType)
        {
            itemType = null;
            if (type.IsArray)
            {
                itemType = type.GetElementType();
                return true;
            }
            return false;
        }
        public static bool IsEnumerable(this Type type, out Type itemType)
        {
            itemType = null;
            if (!type.IsGenericType)
            {
                return false;
            }

            if (!typeof(IEnumerable<>).MakeGenericType(type.GenericTypeArguments).IsAssignableFrom(type))
            {
                return false;
            }
            itemType = type.GenericTypeArguments.FirstOrDefault();
            return true;
        }
    }
}
